package com.zch.market.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zch.market.dao.UserMapper;
import com.zch.market.entity.User;
import com.zch.market.service.UserService;
@Service("us")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper dao;
	//初始化每页最多存放几条数据
	private final int PAGE_SIZE=5;
	@Override
	public Map<String, Object> login(String name,String pwd) {
		Map<String,Object> map = new HashMap<String,Object>();
		User user = dao.getUserByName(name);
		if(user != null){//用户存在
			if(user.getPassword().equals(pwd)){//密码正确
				map.put("isLogin", true);//登录成功还是失败的验证
				map.put("user1", user);//存放正确的用户对象
			}else{//密码错误
				map.put("isLogin", false);
				map.put("errorMsg", "密码错误");
			}
		}else{//用户不存在
			map.put("errorMsg", "用户名不存在");
			map.put("isLogin", false);
		}
		return map;
	}
	@Override
	public List<User> getUserByPage(String userName,int pageIndex) {
		Map<String, Object> map = new HashMap<>();
		map.put("userName",userName);
		//获得当前页第一条数据在查询的数据中的位置
		int firstRow = (pageIndex - 1)*PAGE_SIZE+1;
		//获得当前页最后一条数据在查询的数据中的位置
		int lastRow = pageIndex*PAGE_SIZE;
		map.put("firstRow", firstRow);
		map.put("lastRow", lastRow);
		//获取查询到的用户列表
		List<User> list = dao.getUserByPage(map);
		return list;
	}

	@Override
	public int getTotalPage(String userName) {
		Map<String, Object> map = new HashMap<>();
		map.put("userName",userName);
		// 获取查询到的用户的数量
		int counts = dao.getTotalCount(map);
		//获取查询的数据可以分为几页
		int pageCount = counts%PAGE_SIZE==0?counts/PAGE_SIZE:counts/PAGE_SIZE+1;
		return pageCount;
	}
	@Override
	public int getTotalCount(String userName){
		Map<String, Object> map = new HashMap<>();
		map.put("userName",userName);
		// 获取查询到的用户的数量
		int counts = dao.getTotalCount(map);
		return counts;
	}
	@Override
	public User getUserById(int id) {
		
		return dao.getUserById(id);
	}
	@Override
	public boolean addUser(User user) {
		
		return dao.addUser(user);
	}
	@Override
	public boolean deleteUser(int id) {
		
		return dao.deleteUser(id);
	}
	@Override
	public boolean updateUser(User user) {
		
		return dao.updateUser(user);
	}

}
